import Toast, { hideToast } from 'tdesign-miniprogram/toast'
const app = getApp()

Page({
  onShow() {
    wx.reportAnalytics('enter_mypost_programmatically', {})
    this.getTabBar().setData({active: 'mypost'})
  },
  onShareAppMessage() {
    return {
      title: '首页',
      path: 'page/home/index'
    }
  },
  onShareTimeline() {
    '首页'
  },

  data: {
    loading: {loading: false},
    theme: 'light',
    sh: '', // 键名仅有一个字母时无法model
    page: 1,
    size: 5,
    noMore: false,
    keyPost: {},
    posts: [],
    post: null,
    postActions: [],
    user: null,
    onGlobalUserChange: null,
    visible: {
      del: false
    }
  },

  onLoad() {
    this.data.onGlobalUserChange = this.onGlobalUserChange.bind(this)
    app.watch('user', this.data.onGlobalUserChange)
    this.setData({
      theme: wx.getSystemInfoSync().theme || 'light',
      user: app.globalData.user,
      postActions: [
        // {
        //   name: '置顶',
        //   cb: e => this.setTop(e),
        // },
        {
          name: '范围',
          cb: e => this.go2visibleRange(e),
        },
        {
          name: '删除',
          cb: e => this.showDelConfirm(e),
        },
      ]
    })

    if (wx.onThemeChange) {
      wx.onThemeChange(({theme}) => {
        this.setData({theme})
      })
    }
    if (app.globalData.user) {
      this.data.user = app.globalData.user
      this.onSearch()
    }
  },
  onUnload() {
    app.unWatch('user', this.data.onGlobalUserChange)
  },
  onGlobalUserChange(val, pre) {
    if (val?.openid && val.openid !== pre?.openid) {
      this.data.user = val
      this.onSearch()
    }
    this.setData({
      user: val,
    })
  },
  toast(option) {
    Toast({
      context: this,
      selector: '#t-toast',
      ...option,
    });
  },
  toastHide() {
    hideToast({
      context: this,
      selector: '#t-toast',
    });
  },
  onSearch() {
    this.listData(true)
  },
  listData(refresh) {
    if (refresh === true) {
      this.data.noMore = false
      this.data.page = 1
      this.data.posts = []
      this.data.keyPost = {}
    }
    let { sh, page, size, noMore, keyPost, posts, user } = this.data
    if (noMore) return
    this.setData({
      loading: {loading: true},
      page: page + 1
    })
    wx.cloud.callFunction({
      name: 'post',
      data: {
        action: 'list',
        data: {
          openid: user.openid,
          s: sh,
          page,
          size
        }
      }
    })
    .then(res => {
      let data = res.result.data,
      nm = data.length < size,
      _posts = []
      this.setData({
        noMore: nm,
      })
      data.forEach(i => {
        if (!keyPost[i._id]) {
          _posts.push(i)
          keyPost[i._id] = i
        }
      })
      
      if (_posts.length) {
        this.setData({
          posts: [...posts, ..._posts],
          keyPost: {...keyPost}
        })
      } else {
        this.data.noMore = nm
        this.listData()
      }
    })
    .finally(() => {
      this.setData({
        loading: {loading: false}
      })
    })
  },
  showDelConfirm(e) {
    this.setData({
      visible: {
        ...this.data.visible,
        del: true
      },
      post: e
    })
  },
  hideDelConfirm() {
    this.setData({
      visible: {
        ...this.data.visible,
        del: false
      },
    })
  },
  setTop(e) {
    this.toast({
      theme: 'loading',
      direction: 'column',
      duration: 10000,
    })
    wx.cloud.callFunction({
      name: 'post',
      data: {
        action: 'update',
        data: {
          _id: e._id,
          topTime: new Date(),
        }
      }
    })
    .then(res => {
      e.topTime = new Date().toISOString()
      const posts = this.data.posts.filter(i => i._id !== e._id)
      posts.unshift(e)
      this.setData({
        posts
      })
    })
    .catch(e => {
      this.toast({
        message: '置顶失败，请稍后重试',
      });
    })
    .finally(() => this.toastHide())
  },
  del(e) {
    this.hideDelConfirm()
    this.toast({
      theme: 'loading',
      direction: 'column',
      duration: 10000,
    })
    wx.cloud.callFunction({
      name: 'post',
      data: {
        action: 'remove',
        data: this.data.post._id
      }
    })
    .then(res => {
      this.setData({
        posts: this.data.posts.filter(i => i._id !== this.data.post._id)
      })
    })
    .catch(e => {
      this.toast({
        message: '删除失败，请稍后重试',
      });
    })
    .finally(() => this.toastHide())
  },
  go2visibleRange(e) {
    this.data.post = e
    wx.navigateTo({
      url: '/packagePublish/pages/visible-range/index',
      events: {
        change: (visibleRange) => {
          this.toast({
            theme: 'loading',
            direction: 'column',
            duration: 10000,
          })
          wx.cloud.callFunction({
            name: 'post',
            data: {
              action: 'update',
              data: {
                _id: e._id,
                visibleRange
              }
            }
          })
          .then(res => {
            e.visibleRange = visibleRange
          })
          .catch(e => {
            this.toast({
              message: '修改失败，请稍后重试',
            });
          })
          .finally(() => this.toastHide())
         },
      },
      success: (res) => {
        res.eventChannel.emit('init', { value: e.visibleRange })
      },
    })
  },
})
